<template>
  <PageWrapper contentBackground>
    <template #title>
      <span>打卡</span>
      <Button
        type="primary"
        @click="clockBtnList"
        class="clockBtnList"
        v-if="hasPermission(['system:record:query'])"
      >
        打卡记录
      </Button>
    </template>
    <template #footer>
      <Form name="custom-validation" ref="formRef" :model="formSearch" v-bind="layout">
        <FormItem label="项目" name="projectId">
          <Select
            v-model:value="formSearch.projectId"
            placeholder="请选择项目"
            :disabled="formSearch.deptId ? true : false"
          >
            <SelectOption v-for="item in projectList" :key="item.projectId">
              <span>{{ item.projectName }}</span>
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem has-feedback label="部门" name="deptId">
          <TreeSelect
            v-model:value="formSearch.deptId"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="deptList"
            placeholder="请选择部门"
            tree-default-expand-all
            :replaceFields="replaceFields"
            :disabled="formSearch.projectId ? true : false"
          >
            <template #title="{ key, value }">
              <span style="color: #08c" v-if="key === formSearch.deptId">{{ value }}</span>
            </template>
          </TreeSelect>
        </FormItem>
      </Form>
      <div class="clock">
        <div>签到时间</div>
        <div>
          <Tag :color="checkIn.color" v-if="checkIn != null">{{ checkIn.label }}</Tag
          ><span>{{ clockInTime }}</span>
        </div>
      </div>
      <div class="clock" v-if="infoType">
        <div>签退时间</div>
        <div>
          <Tag :color="checkOut.color" v-if="checkOut != null">{{ checkOut.label }}</Tag
          ><span>{{ checkOutTime }}</span>
        </div>
      </div>
      <div class="clock locate">( 当前地理位置 ) {{ address }}</div>
    </template>
    <div class="clockMap">
      <Map ref="childComp" @update="getFn" />
    </div>
    <div class="signIn" @click="singnIn">{{ title }}</div>
  </PageWrapper>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, ref, nextTick } from 'vue';
import { PageWrapper } from '/@/components/Page';
import Map from '/@/components/Map/Map.vue';
import { attendanceClockIn, attendancePage } from '/@/api/backs/attendance/signIn';
import { deptSimple } from '/@/api/backs/workLog/diary';
import { getProjectUser } from '/@/api/backs/attendance/attendanceManagement';
import { useUserStore } from '/@/store/modules/user';
import { Tag, Form, FormItem, Select, message, TreeSelect, SelectOption } from 'ant-design-vue';
import { Button } from '/@/components/Button';
import { useGo } from '/@/hooks/web/usePage';
import moment from 'moment';
import { usePermission } from '/@/hooks/web/usePermission';

export default defineComponent({
  components: {
    PageWrapper,
    Map,
    Tag,
    Button,
    Form,
    FormItem,
    Select,
    TreeSelect,
    SelectOption,
  },
  setup() {
    const { hasPermission } = usePermission();
    const go = useGo();
    const childComp = ref(null);
    const userStore = useUserStore();
    const formRef = ref();
    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };
    const rules = {
      projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
    };
    const data: any = reactive({
      projectList: [],
      title: '签到',
      center: [],
      userId: userStore.getUserInfo.user.id,
      //打卡
      checkOutTime: '--',
      clockInTime: '--',
      address: '',
      id: null,
      mapInfo: {},
      checkIn: null,
      checkOut: null,
      infoType: true, //判断是自由打卡还是固定打卡
      formSearch: {
        deptId: null,
        projectId: null,
      },
      deptList: [],
      replaceFields: { children: 'children', title: 'name', key: 'id', value: 'id' },
      clockListState: [
        {
          label: '正常',
          value: 'NORMAL_CLOCK',
          color: 'green',
        },
        {
          label: '请假',
          value: 'LEAVE_CLOCK',
          color: 'yellow',
        },
        {
          label: '迟到',
          value: 'LATE_CLOCK',
          color: 'red',
        },
        {
          label: '早退',
          value: 'EARLY_CLOCK',
          color: 'red',
        },
        {
          label: '旷工',
          value: 'ABSENT_CLOCK',
          color: 'red',
        },
        {
          label: '缺卡',
          value: 'MISS_CLOCK',
          color: 'yellow',
        },
        {
          label: '未打卡',
          value: 'NOT_CLOCK',
          color: 'yellow',
        },
      ],
    });
    //根据状态获取颜色
    function getStateColor(val) {
      let arr = null;
      if (data.clockListState && data.clockListState.length && val) {
        data.clockListState.forEach((i) => {
          if (i.value == val) {
            console.log('11111111111');
            arr = i;
          }
        });
      }
      return arr;
    }

    //父子方法获取地址
    function getFn(val) {
      data.mapInfo = val;
      data.address = val.address;
      if (!val.address || !val.lat || !val.lng) {
        message.warning('请刷新页面重新获取定位');
      }
      if (val.lat && val.lng) {
        getAttendanceRecord();
      }
    }
    //我是打卡
    const singnIn = async () => {
      if (JSON.stringify(data.projectInfo) === '{}') return message.error('请选择项目！！！');
      let params = {
        projectId: data.formSearch.projectId,
        deptId: data.formSearch.deptId,
      } as any;
      if (data.mapInfo) {
        params.clockLatitude = data.mapInfo.lat;
        params.clockLongitude = data.mapInfo.lng;
        params.clockPosition = data.mapInfo.address;
      }
      console.log('------', params);
      try {
        await attendanceClockIn(params);
        message.success('打卡成功！');
        getAttendanceRecord();
      } catch (error) {}
    };
    //获取打卡信息
    const getAttendanceRecord = async () => {
      try {
        const state = await attendancePage({
          userId: data.userId,
          longitude: data.mapInfo.lng,
          latitude: data.mapInfo.lat,
        });
        if (state) {
          if (state.attendanceRecord) {
            if(state.attendanceRecord.clockInTime){
              data.clockInTime = `${state.attendanceRecord.attendanceDateStr} ${state.attendanceRecord.clockInTime}  (${state.attendanceRecord.clockInPosition})`;
            }
            if(state.attendanceRecord.clockOffTime){
              data.checkOutTime = `${state.attendanceRecord.attendanceDateStr} ${state.attendanceRecord.clockOffTime}   (${state.attendanceRecord.clockOffPosition})`;
            }
            data.checkIn = getStateColor(state.attendanceRecord.clockInStatus);
            data.checkOut = getStateColor(state.attendanceRecord.clockOffStatus);
          }
          data.formSearch.deptId = state.deptId || null;
          data.formSearch.projectId = state.projectId || null;
          if (state.attendanceType == 'FREEDOM_ATTENDANCE') {
            data.infoType = false;
            data.title = '签到';
          }
          if (state.attendanceType == 'FIXED_ATTENDANCE' && data.clockInTime) {
            data.infoType = true;
            data.title = '签退';
          }
          console.log('我是详情数据', data);
        } else {
        }
      } catch (error) {}
    };
    //获取项目
    const getProjectList = async () => {
      data.projectList = await getProjectUser({ isRecord: 0, userId: data.userId, status: 1 });
      data.projectList.forEach((element) => {
        element.label = element.projectName;
        element.value = element.projectId;
      });
    };
    getProjectList();
    //获取部门
    const getOptions = async () => {
      data.deptList = await deptSimple();
    };
    getOptions();
    //跳转打卡记录
    const clockBtnList = () => {
      go('/attendance/clockList/' + data.userId);
    };
    return {
      ...toRefs(data),
      getAttendanceRecord,
      formRef,
      rules,
      moment,
      clockBtnList,
      childComp,
      singnIn,
      getFn,
      hasPermission,
      getOptions,
      layout,
      getStateColor,
    };
  },
});
</script>
<style lang="less" scoped>
::v-deep(.vben-page-wrapper-content-bg) {
  background: transparent;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

::v-deep(.ant-page-header.has-footer) {
  // padding-bottom: 10px;
}

.clockBtnList {
  margin-left: 20px;
}

.clock {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  margin-bottom: 5px;
  border: 1px solid #f0f5ff;
  color: #333;
  font-size: 16px;
  font-weight: bold;
}

.locate {
  border: none;
  justify-content: flex-end;
}

.clockMap {
  // background-color: #ccc;
  width: 100%;
  height: 400px;
}

.signIn {
  width: 140px;
  height: 140px;
  background: linear-gradient(180deg, #82afff 0%, #3077ff 100%);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32px;
  font-weight: 600;
  margin-top: 10px;
  color: #ffffff;
  cursor: pointer;
}
::v-deep(.ant-form) {
  display: flex;
  justify-content: space-between;
}
::v-deep(.ant-row) {
  width: 100%;
}
</style>
